package com.zzh.zzhaiagent.protection.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

public class IpLocationUtil {
    public static String getCityByIp(String ip) {
        String api = "http://ip-api.com/json/" + ip + "?lang=zh-CN";
        try {
            URL url = new URL(api);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            in.close();
            JSONObject obj = JSONUtil.parseObj(sb.toString());
            System.out.println(obj.toString());
            return obj.getStr("city"); // 还可以获取country、regionName等
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //测试
    public static void main(String[] args) {
        //成功：{"status":"success","country":"中国","countryCode":"CN","region":"BJ","regionName":"北京市","city":"北京","zip":"100000","lat":39.9042,"lon":116.407,"timezone":"Asia/Shanghai","isp":"Beijing Baidu Netcom Science and Technology Co., Ltd.","org":"Beijing Baidu Netcom Science and Technology Co., Ltd.","as":"AS38365 Beijing Baidu Netcom Science and Technology Co., Ltd.","query":"182.61.201.211"}
        //失败：{"status":"fail","message":"private range","query":"192.168.118.201"}
        System.out.println(getCityByIp("182.61.201.211"));
        System.out.println(getCityByIp("baidu.com"));
        System.out.println(getCityByIp("192.168.118.234"));
        System.out.println(getCityByIp("192.168.118.201"));
    }
}